<template>
    <div class="archive-container">
        <div class="glass-bg">
            <!-- <h1 class="archive-title">文章归档</h1> -->

            <div class="archive-content">
                <el-skeleton :loading="loading" animated :rows="10" v-if="loading">
                </el-skeleton>

                <template v-else>
                    <div class="year-section" v-for="(yearGroup, year) in groupedArticles" :key="year">
                        <h2 class="year-title">{{ year }} 年</h2>
                        <el-divider />

                        <div class="article-list">
                            <div class="article-item" v-for="article in yearGroup" :key="article.articleId"
                                @click="openDetail(article.articleId)">
                                <div class="article-inner">
                                    <div class="article-img-container">
                                        <img :src="imgUrl + article.articleImg" class="article-img" alt="文章配图" />
                                        <div class="view-count">
                                            <el-icon>
                                                <View />
                                            </el-icon>
                                            <span>{{ article.viewCount }}</span>
                                        </div>
                                    </div>
                                    <div class="article-meta">
                                        <h3 class="article-title">{{ article.articleTitle }}</h3>
                                        <div class="article-info">
                                            <span class="article-date">
                                                <el-icon>
                                                    <Calendar />
                                                </el-icon>
                                                {{ formatDate(article.createTime) }}
                                            </span>
                                            <el-tag size="small" effect="light" class="article-category">
                                                {{ article.categoryName }}
                                            </el-tag>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div v-if="noMoreData" class="no-more">-- 没有更多文章了 --</div>
                    <div v-if="!noMoreData" class="loading-more" ref="loadMoreTrigger">
                        <el-icon class="loading-icon" v-if="loadingMore">
                            <Loading />
                        </el-icon>
                        <span>{{ loadingMore ? '加载中...' : '向下滑动加载更多' }}</span>
                    </div>
                </template>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Calendar, View, Loading } from '@element-plus/icons-vue'
import { listHome } from '@/api/bk/home.js' // 确保导入了您的API函数


const imgUrl = import.meta.env.VITE_API_BASE_URL
const router = useRouter()
const loading = ref(true)
const loadingMore = ref(false)
const homeList = ref([])
const total = ref(0)
const noMoreData = ref(false)
const loadMoreTrigger = ref(null)
const queryParams = ref({
    pageNum: 1,
    pageSize: 16  // 增加每页条数以适应更紧凑的布局
})

// 获取文章列表
const getList = (isLoadMore = false) => {
    if (isLoadMore) {
        loadingMore.value = true
    } else {
        loading.value = true
    }

    listHome(queryParams.value).then(response => {
        if (isLoadMore) {
            homeList.value = [...homeList.value, ...response.rows]
        } else {
            homeList.value = response.rows
        }
        total.value = response.total

        // 检查是否还有更多数据
        if (homeList.value.length >= total.value) {
            noMoreData.value = true
        }

        loading.value = false
        loadingMore.value = false
    }).catch(error => {
        ElMessage.error('获取文章列表失败')
        loading.value = false
        loadingMore.value = false
    })
}



// 监听滚动事件设置懒加载
const setupIntersectionObserver = () => {
    if (!loadMoreTrigger.value) return

    const observer = new IntersectionObserver((entries) => {
        const trigger = entries[0]
        if (trigger.isIntersecting && !noMoreData.value && !loadingMore.value) {
            loadMore()
        }
    }, {
        rootMargin: '0px 0px 200px 0px'  // 增加预加载距离，提前触发加载
    })

    observer.observe(loadMoreTrigger.value)

    return () => {
        if (loadMoreTrigger.value) {
            observer.unobserve(loadMoreTrigger.value)
        }
    }
}

// 加载更多数据
const loadMore = () => {
    if (loadingMore.value || noMoreData.value) return

    queryParams.value.pageNum += 1
    getList(true)
}

// 初始化页面
onMounted(() => {
    getList()
    nextTick(() => {
        setupIntersectionObserver()
    })
})

// 按照年份对文章进行分组
const groupedArticles = computed(() => {
    const groups = {}

    homeList.value.forEach(article => {
        // 过滤掉categoryId为4的文章
        if (article.categoryId === 4) return

        const year = new Date(article.createTime).getFullYear()
        if (!groups[year]) {
            groups[year] = []
        }
        groups[year].push(article)
    })

    // 对年份进行降序排列
    return Object.fromEntries(
        Object.entries(groups).sort((a, b) => b[0] - a[0])
    )
})

// 格式化日期
const formatDate = (dateString) => {
    const date = new Date(dateString)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
}

// 文章详情页跳转
const openDetail = (id) => {
    const url = router.resolve({
        name: 'Detail',
        params: { id }
    }).href
    window.open(url, '_blank')
}

// 监听homeList变化，当列表更新后设置观察器
watch(homeList, () => {
    nextTick(() => {
        setupIntersectionObserver()
    })
})
</script>

<style scoped>
.archive-container {
    padding: 0.4rem;
    min-height: calc(100vh - 1rem);
    position: relative;
}

.glass-bg {
    background: rgba(255, 255, 255, 0.6);
    backdrop-filter: blur(0.1rem);
    border-radius: 0.15rem;
    box-shadow: 0 0.03rem 0.1rem rgba(0, 0, 0, 0.08);
    padding: 0.25rem;
    position: relative;
    overflow: hidden;
}

.glass-bg::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0.1) 100%);
    z-index: -1;
}

.archive-title {
    font-size: 0.35rem;
    color: #333;
    text-align: center;
    margin-bottom: 0.25rem;
    position: relative;
    overflow: hidden;
}

.archive-title::after {
    content: '';
    position: absolute;
    bottom: -0.05rem;
    left: 50%;
    width: 1.8rem;
    height: 0.03rem;
    background: linear-gradient(90deg, transparent, #409EFF, transparent);
    transform: translateX(-50%);
}

.archive-content {
    margin-top: 0.15rem;
}

.year-title {
    font-size: 0.15rem;
    color: #409EFF;
    margin-bottom: 0.08rem;
    display: inline-block;
    position: relative;
}

.year-section {
    margin-bottom: 0.3rem;
    transition: all 0.3s ease;
}

.article-list {
    margin-top: 0.15rem;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(3.5rem, 1fr));
    gap: 0.15rem;
}

.article-item {
    padding: 0.12rem;
    border-radius: 0.08rem;
    transition: all 0.3s ease;
    cursor: pointer;
    border: 0.01rem solid rgba(0, 0, 0, 0.03);
    background-color: rgba(255, 255, 255, 0.5);
}

.article-inner {
    display: flex;
    align-items: center;
    gap: 0.12rem;
}

.article-item:hover {
    transform: translateY(-0.03rem);
    box-shadow: 0 0.03rem 0.15rem rgba(64, 158, 255, 0.15);
    background-color: rgba(255, 255, 255, 0.9);
}

.article-img-container {
    position: relative;
    width: 0.8rem;
    height: 0.6rem;
    min-width: 0.8rem;
    overflow: hidden;
    border-radius: 0.06rem;
    flex-shrink: 0;
}

.article-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.5s ease;
}

.article-item:hover .article-img {
    transform: scale(1.05);
}

.view-count {
    position: absolute;
    bottom: 0.04rem;
    right: 0.04rem;
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    padding: 0.01rem 0.05rem;
    border-radius: 0.04rem;
    font-size: 16px;
    display: flex;
    align-items: center;
}

.view-count .el-icon {
    margin-right: 0.03rem;
    font-size: 16px;
}

.article-meta {
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    min-width: 0;
}

.article-title {
    font-size: 0.14rem;
    margin: 0;
    margin-bottom: 0.03rem;
    color: #333;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    transition: color 0.3s;
}

.article-item:hover .article-title {
    color: #409EFF;
}

.article-info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 0.11rem;
}

.article-date {
    color: #888;
    display: flex;
    align-items: center;
    white-space: nowrap;
}

.article-date .el-icon {
    margin-right: 0.04rem;
    font-size: 0.11rem;
}

.article-category {
    flex-shrink: 0;
    font-size: 0.11rem;
}

.loading-more,
.no-more {
    text-align: center;
    padding: 0.15rem 0;
    color: #999;
    font-size: 0.13rem;
}

.loading-icon {
    animation: rotating 2s linear infinite;
    margin-right: 0.05rem;
}

@keyframes rotating {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}

:deep(.el-divider) {
    margin: 0.08rem 0;
}

/* 添加页面进入动画 */
@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(0.15rem);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.archive-container {
    animation: fadeIn 0.6s ease-out;
}

/* 响应式调整 */
@media (max-width: 768px) {
    .article-list {
        grid-template-columns: repeat(auto-fill, minmax(100%, 1fr));
    }

    .article-img-container {
        width: 0.9rem;
        height: 0.7rem;
    }
}
</style>